package com.itheima.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.bean.Employee;
import com.itheima.common.PageParam;
import com.itheima.common.R;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;


@RequestMapping("/employee")
@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;


    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session){

        String md5Password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());

        employee.setPassword(md5Password);

        Employee em = employeeService.login(employee);

        if (em != null){
            session.setAttribute("employee", em);
            return R.success(em);
        }
        return R.error("登录失败");
    }

    /**
     * 添加用户
     * @param employee
     * @return
     */
    @PostMapping
    public R add(@RequestBody Employee employee){

        String md5Password = DigestUtils.md5DigestAsHex("123456".getBytes());

        employee.setPassword(md5Password);

        int row = employeeService.add(employee);
        if (row>0) return R.success("添加成功");

        return R.error("添加失败");
    }

    /**
     * 用户登出
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpSession session){

        session.invalidate();
        return R.success("用户登出成功");
    }

    /**
     * 用户分页查询
     * @param pageParam
     * @return
     */
    @GetMapping("/page")
    public R findPage(PageParam pageParam){

        IPage page = employeeService.findPage(pageParam);

        return R.success(page);
    }

    /**
     * 更新用户
     * @param employee
     * @return
     */
    @PutMapping
    public R update(@RequestBody Employee employee){

        int row = employeeService.update(employee);
        if (row>0) return R.success("更新成功");

        return R.error("更新失败");

    }

}
